//
//  SinaUserAccountViewModel.m
//  MySinaWeiboProjectForOC
//
//  Created by apple on 2016/11/17.
//  Copyright © 2016年 WangChen. All rights reserved.
//

#import "SinaUserAccountViewModel.h"
#import "MyAFNTools.h"

@interface SinaUserAccountViewModel ()
//判断是否过期
@property (nonatomic,assign) BOOL isExperis;
@end


@implementation SinaUserAccountViewModel

//单例
+(instancetype)shared{
    
    static id accountShared;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        accountShared = [[self alloc]init];
    });
    return accountShared;
}


//初始化时就直接从沙盒中取出
- (instancetype)init
{
    self = [super init];
    if (self) {
        [self loadAccountUnarchiverdOut];
    }
    return self;
}


//重写判断是否已经登录的方法
-(BOOL)isLogin{
    
    if(self.userAccountModel.access_token && !self.isExperis){
        return YES;
    }
    return NO;
}

-(BOOL)isExperis{
    
    if([[NSDate date] compare:self.userAccountModel.expires_date] == NSOrderedDescending){
        return YES;
    }
    return false;
}


//用户头像地址
-(NSURL *)iconURL{
    
    NSString *urlStr = self.userAccountModel.avatar_large;
    NSURL *url = [[NSURL alloc]initWithString:urlStr];
    return url;
}



#pragma mark
#pragma mark - 访问token
-(void)accessTheTokenWithCode:(NSString *)code finishBlock:(void(^)(BOOL res))finish{
    
    NSDictionary *parameter = @{@"client_id" : appKey,
                                @"client_secret" : appSecret,
                                @"grant_type" : @"authorization_code",
                                @"code" : code,
                                @"redirect_uri" : redirectUrlStr};
    
    NSString *urlStr = accessToken;
    
    [[MyAFNTools sharedOwnTool] requestWithURLStr:urlStr method:POST paramter:parameter complete:^(NSDictionary* responseObj, NSError *error) {
        if(error){
//            [SVProgressHUD showErrorWithStatus:@"世界上最远的距离就是没有网络"];
            finish(NO);
            return;
        }
        //从获得的数据得到uid token 并访问用户信息
        [self getUserInfoByAccessUserShowWithDict:responseObj finishBlock:finish];
        
        
    }];
    
}


#pragma mark
#pragma mark - 访问用户信息
-(void)getUserInfoByAccessUserShowWithDict:(NSDictionary *)dict finishBlock:(void(^)(BOOL res))finish{
    
    NSDictionary *paramters = @{@"access_token":dict[@"access_token"],@"uid":dict[@"uid"]};
    
    [[MyAFNTools sharedOwnTool]requestWithURLStr:userShowURLString method:GET paramter:paramters complete:^(NSDictionary *responseObj, NSError *error) {
        
        if(error){
            NSLog(@"%@",error);
//            [SVProgressHUD showErrorWithStatus:@"世界上最远的距离就是没有网络.."];
            finish(NO);
            return;
        }
        
        //合并两次的信息
        NSMutableDictionary *mDict = responseObj.mutableCopy;
        [dict enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
            [mDict setObject:obj forKey:key];
        }];
        
        //kvc转化为Model
        SinaUserAccountModel *userAccountModel = [[SinaUserAccountModel alloc]init];
        [userAccountModel setValuesForKeysWithDictionary:mDict];
        //给全局userAccountModel赋值
        self.userAccountModel = userAccountModel;
        
        //归档
        [self saveAccountArchiverdIn];
        
        finish(YES);
    }];
    
    
    
}




#pragma mark
#pragma mark - 归档存入沙盒
-(void)saveAccountArchiverdIn{
    
    NSString *filePath = userAccountSavePath;
    
    [NSKeyedArchiver archiveRootObject:self.userAccountModel toFile:filePath];
    
}




#pragma mark
#pragma mark - 解档取出数据
-(void)loadAccountUnarchiverdOut{
    
    NSString *filePath = userAccountSavePath;
    
    self.userAccountModel = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
    
}





@end
